<?php  
class Pdohelper{
    
    public $sth;  
    public $dbh;
    
    private $db_name;
  
    public function __construct($config)  
    {
       $dsn = 'mysql:host='.$config['hostname']. ';dbname='.$config['database']; 
       $this->db_name=$config['database'];
       if(!empty($config['port'])) {
           $dsn  .= ';port='.$config['port'];
       }
       try {  
            $this->dbh = new PDO($dsn,$config['username'],$config['password']);  
        } catch (PDOException $e) {  
            exit('连接失败:' . $e->getMessage());  
        }  
        $this->dbh->query('SET NAMES ' .$config['charset']);  
    }
    
    /**
     * 执行一条sql语句
     * @param unknown $sql
     */
    public function query($sql){
        $this->sth = $this->dbh->prepare($sql);
        return $this->sth->execute();
    }
  
    /** 返回单条数据 
     * @param $sql 
     * @param bool $debug 
     */  
    public function getRow($sql){
        $this->sth = $this->dbh->prepare($sql);
        $this->sth->execute();
        return $this->sth->fetch(PDO::FETCH_ASSOC);
    }
    
    /** 返回多条数据
     * @param $sql
     * @param bool $debug
     */
    public function getAll($sql){
        $this->sth = $this->dbh->prepare($sql);
        $this->sth->execute();
        return $this->sth->fetchAll(PDO::FETCH_ASSOC);
    }
    
    public function getOne($sql){
        $this->sth = $this->dbh->prepare($sql);
        $this->sth->execute();
        return $this->sth->fetchColumn();
    }
    
    /**
     * @comment 插入数据
     */
    public function insert($table, $args, $debug = null)
    {
        $sql = "INSERT INTO `$table` SET ";
        $code = $this->getCode($table, $args);
        $sql .= $code;
        if ($debug) echo $sql;
        if ($this->dbh->exec($sql)) {
            return $this->dbh->lastInsertId();
        }
        return false;
    }
  
    //修改数据  
    public function update($table, $args, $condition, $debug = null)  
    {  
        $code = $this->getCode($table, $args);  
        $sql = "UPDATE `$table` SET ";  
        $sql .= $code;  
        if (false !== ($con = $this->getCondition($condition))) {  
            $sql .= $con;  
        }  
        if ($debug) echo $sql;
        return $this->dbh->exec($sql);
    }
  
    //删除记录  
    public function delete($table, $condition, $debug = false)  
    {  
        $sql = "DELETE FROM `$table`";  
        if (false !== ($con = $this->getCondition($condition))) {  
            $sql .= $con;  
        } else {  
            exit('条件错误!');  
        }  
        if ($debug) echo $sql; 
        return $this->dbh->exec($sql);
    }
    
    //获取数据表里的字段
    public function getFields($table)
    {
        $this->sth = $this->dbh->query("DESCRIBE $table");
        $this->sth->setFetchMode(PDO::FETCH_ASSOC);
        $result = $this->sth->fetchAll();
        $this->sth = null;
        return $result;
    }
    
    public function getAllTable()
    {
        $sql = "show tables";
        $rows = $this->doSql($sql);
        $tables = array();
        foreach ($rows as $row) {
            $items = array();
            $table = $row['Tables_in_' .$this->$db_name];
            $sql = "show columns from  {$table}";
            $items = $this->doSql($sql);
            $columns = array();
            foreach ($items as $item) {
                $columns[] = $item['Field'];
            }
            $tables[$table] = $columns;
        }
        return $tables;
    }
    
    //获取记录总数
    public function counts($table, $condition = '', $debug = false)
    {
        $sql = "SELECT COUNT(*) AS num FROM `$table`";
        if (false !== ($con = $this->getCondition($condition))) {
            $sql .= $con;
        }
        if ($debug) echo $sql;
        $count = $this->dbh->query($sql);
        return $count->fetchColumn();
    }
    
    /**
     * 捕获PDO错误信息
     */
    public function getError()
    {
        return $this->dbh->errorInfo();
    }
    
    //获取要操作的数据
    private function getCode($table, $args)
    {
        $code = '';
        if (is_array($args)) {
            foreach ($args as $k => $v) {
                $code .= "`$k`='$v',";
            }
        }
        $code = substr($code, 0, -1);
        return $code;
    }
    
    //获取查询条件
    private function getCondition($condition = '')
    {
        if ($condition != '') {
            $con = ' WHERE 1=1 ';
            if (is_array($condition)) {
                foreach ($condition as $k => $v) {
                    $con .= " AND $k = '$v'";
                }
            } elseif (is_string($condition)) {
                $con .= "AND $condition";
            } else {
                return false;
            }
            return $con;
        }
        return false;
    }
    
    
    /*** 返回多条数据
     * @param $sql
     * @param string $model
     * @param bool $debug
     * @return mixed
     */
    private function doSql($sql)
    {
        $this->sth = $this->dbh->query($sql);
        $this->sth->setFetchMode(PDO::FETCH_ASSOC);
        $result = $this->sth->fetchAll();
        $this->sth = null;
        return $result;
    }
  
    //关闭数据连接  
    public function __destruct()  
    {  
        $this->dbh = null;  
    }  
}  